package com.superatom.concurrent.basic.lock;

import java.util.concurrent.locks.LockSupport;

public class WaitAndNotify {
    private Object gold = null;

    public static void main(String[] args) throws InterruptedException {
        WaitAndNotify waitAndNotify = new WaitAndNotify();
        //waitAndNotify.waitGold();
        waitAndNotify.parkUnparkWaitGold();
    }

    private void waitGold() throws InterruptedException {
        gold = null;
        Thread thread = new Thread(() -> {
            if (gold == null){
                try {
                    // 导致两个线程死锁
                    // Thread.sleep(5000l);
                    synchronized (this){
                        System.out.println("1.等待黄金的到来");
                        this.wait();
                    }
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println("2.拿到黄金");
        });

        thread.start();
        Thread.sleep(3000);

        // 找到黄金
        gold = new Object();
        synchronized (this) {
            this.notifyAll();
            System.out.println("3.通知消费者");
        }
    }

    private void parkUnparkWaitGold() throws InterruptedException {
        gold = null;
        Thread thread = new Thread(() -> {
            if (gold == null){
                try {
                    Thread.sleep(5000l);
                    System.out.println("1.等待黄金的到来");
                    // 将当前线程挂起，等待继续运行的许可
                    LockSupport.park();
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println("2.拿到黄金");
        });

        thread.start();
        Thread.sleep(3000);

        // 找到黄金
        gold = new Object();
        System.out.println("3.通知消费者");
        // 给指定的线程，颁发继续运行的许可（好比一个信号）
        LockSupport.unpark(thread);
    }
}
